/**
 * Created by chenxq on 2018/1/1.
 */
import React,{Component} from 'react';
import { Table, Button, Input, message, InputNumber,Popconfirm, Divider, Select,Radio} from 'antd';
import styles from './style.less';
import request from '../../utils/request';
import uuid from '../../utils/uuid';
import {reg} from '../../utils/CheckList';
export default class extends Component{
  constructor(props){
    super(props);
    let list= this.props.list || [];
    list.forEach(item=>{
      item.key=uuid();
      if(item.cardNo){
        item.cardNo=item.cardNo.replace(/(\d{4})(?=\d)/g, "$1 ");
      }
    });
    this.sourceList=[...list];
    this.state={
      list,
    }
  }


  columns=[{
    title:'信用卡号',
    dataIndex:'cardNo',
    render:(val,record)=>{
      if(record.editable){
        return <Input value={val}
                      placeholder="请输入信用卡号"
                      maxLength='23'
                      onChange={e => this.handleFieldChange(e.target.value, 'cardNo', record.key)}
        />
      }else{
        return val;
      }
    }
  },{
    title:'授信额度',
    dataIndex:'credit',
    render:(val,record)=>{
      if(record.editable){
        return <Input value={val}
                      placeholder="请输入授信额度"
                      onChange={e => this.handleFieldChange(e.target.value, 'credit', record.key)}

        />
      }else{
        return val;
      }
    }
  },{
    title:'发卡时间',
    dataIndex:'grantTime',
    render:(val,record)=>{
      if(record.editable){
        return <Input value={val}
                      placeholder="请输入发卡时间"
                      onChange={e => this.handleFieldChange(e.target.value, 'grantTime', record.key)}
        />
      }else{
        return val;
      }
    }
  },{
    title:'操作',
    dataIndex:'key',
    render:(key,record)=>{
      if (record.editable) {
        if (record.isNew){
          return (
            <span>
                <a onClick={(e)=>this.save(e,record)}>保存</a>
                <Divider type="vertical" />
                <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}>
                  <a>删除</a>
                </Popconfirm>
              </span>
          );
        }
        return (
          <span>
              <a onClick={(e)=>this.save(e,record)}>保存</a>
              <Divider type="vertical" />
              <a onClick={e =>this.toggleEditable(e, record,false)}>取消</a>
            </span>
        );
      }
      return (
        <span>
            <a onClick={e => this.toggleEditable(e, record,true)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record)}>
              <a>删除</a>
            </Popconfirm>
          </span>
      );
    }
  }]
  handleFieldChange=(val,fieldName,key)=>{
    const newData = [...this.state.list];
    const target = this.getRowByKey(key);
    if (target) {
      if(fieldName=='cardNo'){
        val=val.replace(/\s+/g, "");
        if(!/^\d{0,}$/.test(val)){
          return ;
        }
        val=val.replace(/(\d{4})(?=\d)/g, "$1 ")
      }
      target[fieldName] = val;
      this.setState({ list: newData });
    }
  }

  save=(e,info)=>{
    e.preventDefault();
    const target = this.getRowByKey(info.key);
    let {cardNo,credit,grantTime} = target;
    cardNo= cardNo.replace(/\s+/g, "");
    if(!cardNo){
      message.error('信用卡号不能为空');
      return ;
    }
    if(cardNo.length<16){
      message.error('信用卡号格式不正确');
      return ;
    }
    if(credit && !reg.money.test(credit)){
      message.error('授信额度格式不正确');
      return ;
    }
    let _this=this;
    let list=[..._this.sourceList];
    var curObj={};
    if(target.isNew){
      list.push(target);
      curObj=list[list.length-1];
    }else{
      curObj=list.find(item=>item.key===target.key);
      curObj=Object.assign(curObj,target);
    }
    this.props.updateList && this.props.updateList(list).then(jsonData=>{
      if(jsonData.result){
        curObj.editable=false;
        delete curObj.isNew;
        _this.sourceList=[...list];
        _this.setState({
          list:[...list]
        })
      }
    });
  }

  remove=(info)=>{
    if(info.isNew){
      const list = this.state.list.filter(item => item.key !== info.key);
      this.setState({ list });
    }else{
      // todo  删除
      let _this=this;
      let list=[..._this.sourceList];
      let index=list.findIndex(item=>item.key==info.key);
      list.splice(index,1);
      this.props.updateList && this.props.updateList(list).then(jsonData=>{
        if(jsonData.result){
          _this.sourceList=[...list];
          _this.setState({
            list:[...list]
          })
        }
      });
    }

  }

  cacheOriginData={};
  index=0;

  addData=()=>{
    let list=[...this.state.list];
    let obj={
      cardNo:'',
      credit:'',
      grantTime:''
    };
    obj.key=uuid();
    obj.editable=true;
    obj.isNew=true;
    list.push(obj);
    this.index+=1;
    this.setState({
      list:list
    })
  }

  getRowByKey(key) {
    return this.state.list.find(item => item.key === key);
  }

  toggleEditable=(e,info,editable=true)=>{
    e.preventDefault();
    let target = this.getRowByKey(info.key);
    if(editable==true){
      this.cacheOriginData[info.key]={
        ...target   //记录下来  取消的时候方便还原
      }
    }else{
      if (this.cacheOriginData[info.key]) {
        Object.assign(target, this.cacheOriginData[info.key]);
        delete this.cacheOriginData[info.key];
      }
    }
    target.editable = editable;
    this.setState({ list: [...this.state.list]});
  }

  render(){
    return(<div style={this.props.style}>
        <Table
          columns={this.columns}
          dataSource={this.state.list}
          pagination={false}
          rowClassName={(record) => {
            return record.editable ? styles.editable : '';
          }}
        />
        <Button
          style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
          type="dashed"
          onClick={this.addData}
          icon="plus"
        >
          新增信用卡
        </Button>
      </div>
    )
  }
}
